/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package filesecurity;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author lehoangkhanh
 */
public class DigitalSign {
    public static byte[] sign(byte[] data, PrivateKey prikey){
        try {        
            Signature dsIns = Signature.getInstance("SHA256withRSA");
            dsIns.initSign(prikey);
            dsIns.update(data);
            byte[] sign = dsIns.sign();
            return sign;
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(DigitalSign.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InvalidKeyException ex) {
            Logger.getLogger(DigitalSign.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SignatureException ex) {
            Logger.getLogger(DigitalSign.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }
    public static boolean verify(byte[] data, byte[] sign, PublicKey pubkey){
        try {
            Signature dsIns = Signature.getInstance("SHA256withRSA");
            dsIns.initVerify(pubkey);
            dsIns.update(data);
            boolean verifies = dsIns.verify(sign);
            return verifies;
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(DigitalSign.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SignatureException ex) {
            Logger.getLogger(DigitalSign.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InvalidKeyException ex) {
            Logger.getLogger(DigitalSign.class.getName()).log(Level.SEVERE, null, ex);
        } 
        return false;
    }
}
